<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">添加</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="图片ID" min-width="150" prop="id" />
        <el-table-column align="left" label="图片" min-width="150" prop="image_url">
          <template #default="scope">
            <div v-if="scope.row.image_url">
              <img :src="scope.row.image_url" alt class="avatar" />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="上传时间" min-width="150" prop="created_at" />
        <el-table-column align="left" label="修改时间" min-width="150" prop="updated_at" />
        <el-table-column align="left" label="图片说明" min-width="150" prop="caption" />
        <el-table-column align="left" label="跳转地址" min-width="150" prop="skip_url" />
        <el-table-column align="left" label="显示顺序" min-width="150" prop="order_num" />
        <el-table-column align="left" label="状态" min-width="150">
          <template #default="scope">
            <span>{{ displayStatus(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作" min-width="150">
          <template #default="scope">
            <span class="edit" style="cursor: pointer;" @click="fnChange(scope.row)">修改</span>
            <span
              class="del"
              style="color: #f00;margin-left: 10px;cursor: pointer;"
              @click="fnDelete(scope.row)"
            >删除</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="page_size"
          :page-sizes="[10, 30, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
      v-model="dialogFormVisible"
      size="50%"
      :before-close="closeDialog"
      :show-close="false"
    >
      <template #header>
        <span class="text-lg">轮播图{{ isChange ? "修改" : "添加" }}</span>
        <div>
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="changeState">确 定</el-button>
        </div>
      </template>
      <el-form ref="uploadForm" class="upload" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片上传" prop="image_url">
          <el-upload
            action="/api/fileUploadAndDownload/upload"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="BeforeLoad"
            :multiple="false"
          >
            <div class="img-box" v-if="form.image_url">
              <img :src="form.image_url" class="img" />
            </div>
            <div class="upload-btn">
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="skip_url" label="跳转地址">
          <el-input type="textarea" placeholder="跳转地址" v-model="form.skip_url" />
        </el-form-item>
        <el-form-item prop="caption" label="图片说明">
          <el-input placeholder="图片说明" v-model="form.caption" />
        </el-form-item>
        <el-form-item prop="order_num" label="显示顺序">
          <el-input placeholder="显示顺序" v-model="form.order_num" />
        </el-form-item>
        <el-form-item prop="status" label="图片状态">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { carouselList, carouselAdd, carouselPut, carouselDel } from "@/api/api";
import { isImageMime } from "@/utils/image";
let searchInfo = ref({});
let page_size = ref(10);
let page = ref(1);
let tableData = ref([]);
let totals = ref(0);
let dialogFormVisible = ref(false);
let form = ref({
  image_url: "",
  caption: "",
  skip_url: "",
  order_num: "",
  status: ""
});
const rules = ref({
  image_url: [{ required: true, message: "请上传图片", trigger: "blur" }],
  caption: [{ required: true, message: "请输入备注", trigger: "blur" }],
  skip_url: [{ required: true, message: "请输入跳转地址", trigger: "blur" }],
  order_num: [{ required: true, message: "请输入显示顺序", trigger: "blur" }],
  status: [{ required: true, message: "请选择图片状态", trigger: "blur" }]
});
let isChange = ref(false);
const uploadForm = ref();
const createDate = ref([
  `${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}`,
  `${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}`
]);
// const createDate = ref([new Date().getTime(), new Date().getTime()]);
onMounted(() => {
  getList();
});

const handleExceed = files => {
  ElMessage({
    message: "最多上传一张图片",
    type: "error"
  });
};
const BeforeLoad = file => {
  if (file.size > 5 * 1024 * 1024) {
    ElMessage({
      message: "当前文件大于5M，请重新选择",
      type: "error"
    });
    return;
  } else {
    const isImage = isImageMime(file.type);
    let pass = true;
    if (!isImage) {
      ElMessage.error("只能上传 jpg,png,svg,webp 格式的图片!");
      pass = false;
    }
    return pass;
  }
};
const uploadSuccess = res => {
  const { data } = res;
  if (data.file) {
    form.value.image_url = data.file.url;
  }
};

const displayStatus = computed(() => {
  return val => {
    if (val === 1) {
      return "正常";
    } else {
      return "禁用";
    }
  };
});
const openDialog = () => {
  isChange.value = false;
  form.value = {
    image_url: "",
    caption: "",
    skip_url: "",
    order_num: "",
    status: ""
  };
  dialogFormVisible.value = true;
};
const fnChange = row => {
  isChange.value = true;
  form.value = JSON.parse(JSON.stringify(row));
  dialogFormVisible.value = true;
};
const fnDelete = row => {
  ElMessageBox.confirm("是否删除该条数据", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params = {
        id: row.id
      };
      const response = await carouselDel(params);
      if (response.code === 200) {
        ElMessage({
          type: "success",
          message: "删除成功!"
        });
        getList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
const closeDialog = () => {
  form.value = {
    image_url: "",
    caption: "",
    skip_url: "",
    order_num: "",
    status: ""
  };
  uploadForm.value.resetFields();
  dialogFormVisible.value = false;
};
const changeState = row => {
  let params = {
    id: form.value.id,
    status: form.value.status,
    image_url: form.value.image_url,
    caption: form.value.caption,
    skip_url: form.value.skip_url,
    order_num:
      form.value.order_num || form.value.order_num == 0
        ? Number(form.value.order_num)
        : ""
  };
  uploadForm.value.validate(async valid => {
    if (valid) {
      if (isChange.value) {
        carouselPut(params).then(response => {
          if (response.code === 200) {
            ElMessage({
              message: "修改成功",
              type: "success"
            });
            closeDialog();
            page.value = 1;
            page_size.value = 10;
            getList();
          }
        });
      } else {
        carouselAdd(params).then(response => {
          if (response.code === 200) {
            ElMessage({
              message: "添加成功",
              type: "success"
            });
            closeDialog();
            page.value = 1;
            page_size.value = 10;
            getList();
          }
        });
      }
    }
  });
};
const getList = () => {
  let params = {};
  carouselList(params).then(response => {
    if (response.code === 200) {
      tableData.value = response.data.rows || [];
      totals.value = response.data.total_rows;
    }
  });
};
const sortChange = (value, row, column) => {
  console.log(value);
  console.log(row);
  console.log(column);
};
const handleCurrentChange = val => {
  page.value = val;
  getList();
};
const handleSizeChange = val => {
  page_size.value = val;
  getList();
};
const onSubmit = () => {
  page.value = 1;
  page_size.value = 10;
  getList();
};
const onReset = () => {
  searchInfo.value = {};
  page.value = 1;
  page_size.value = 10;
  createDate.value = [
    `${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}`,
    `${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}`
  ];
  getList();
};
</script>
<style lang="scss" scoped>
.el-form-item {
  width: 300px;
}
.avatar {
  width: 100%;
  height: 90px;
  margin-right: 10px;
  object-fit: fill;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  text-align: center;
  border: 1px solid #f6f2f3;
}
.el-icon.avatar-uploader-icon:hover {
  box-shadow: 0 0 2px 4px rgba(246, 242, 243, 0.3);
}
.img-box:hover {
  box-shadow: 0 0 2px 4px rgba(246, 242, 243, 0.3);
}
.img-box {
  width: 180px;
  height: 180px;
  border: 1px solid #f6f2f3;
  padding: 4px;
  border-radius: 4px;
  box-sizing: border-box;
  margin-right: 10px;
  .img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
.upload {
  .el-form-item {
    width: 400px;
  }
}
</style>
